#include "SearchList.h"
#include<qstandarditemmodel.h>
#include"MusicListView.h"
#include"MusicListDelegate.h"
#include<qboxlayout.h>

SearchList::SearchList(QWidget *parent)
	: QWidget(parent),
	m_model(new QStandardItemModel(this)),
	m_delegate(new MusicListDelegate(this)),
	m_listView(new MusicListView(this))
{
	m_listView->setModel(m_model);
	m_listView->setItemDelegate(m_delegate);
	QVBoxLayout* layOut = new QVBoxLayout(this);
	layOut->addWidget(m_listView);

	initConnect();
}

SearchList::~SearchList()
{}


void SearchList::appendSong(const QList< OnlionMusicInfo>& infos)
{
	m_model->clear();

	for (auto& i : infos)
	{
		QStandardItem* item = new QStandardItem;
		item->setData(":/icons/defaultCover.png", Qt::UserRole + 1);
		item->setData(i.songName, Qt::UserRole + 2);
		item->setData(i.singerName, Qt::UserRole + 3);
		item->setData(i.duration_s, Qt::UserRole + 4);
		item->setData(i.url, Qt::UserRole + 5);
		m_model->appendRow(item);
	}
	
	
}

void SearchList::appendUrl(const QList<QUrl>& urlList)
{
	for (int i = 0; i < m_model->rowCount(); i++)
	{
		auto index = m_model->index(i,0);
		auto item = m_model->itemFromIndex(index);
		QUrl url = urlList[i];
		if (url.isEmpty())
		{
			item->setFlags(Qt::ItemFlag::NoItemFlags);
		}
		qDebug() << "url[" << i <<"] = " << url;
		item->setData(url, Qt::UserRole + 5);
	}
}

void SearchList::push_back(const QList<OnlionMusicInfo>& infos)
{
	appendSong(infos);
}

void SearchList::scrollTop()
{
	m_listView->scrollToTop();
}

void SearchList::push_back(const QList<Song>& list)
{
	appendSong(list);
}

void SearchList::initConnect()
{
	connect(m_listView, &MusicListView::mouseLeftDoubleClicked,
		[this](const QModelIndex& index) {
			Song s;
			s.cover = index.data(Qt::UserRole + 1).toString();
			s.songName = index.data(Qt::UserRole + 2).toString();
			s.singerName = index.data(Qt::UserRole + 3).toString();
			s.duration_s = index.data(Qt::UserRole + 4).toInt();
			s.url = index.data( Qt::UserRole + 5).toUrl();

			emit mouseLeftDoubleClicked(std::move(s));
		});
}

void SearchList::appendSong(const QList<Song>& list)
{

	m_model->clear();
	for (auto& i : list)
	{
		QStandardItem* item = new QStandardItem;
		item->setData(i.cover, Qt::UserRole + 1);
		item->setData(i.songName, Qt::UserRole + 2);
		item->setData(i.singerName, Qt::UserRole + 3);
		item->setData(i.duration_s, Qt::UserRole + 4);
		item->setData(i.url, Qt::UserRole + 5);
		//item->setData(false, Qt::UserRole + 6);
		m_model->appendRow(item);
	}

}

